<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2018/10/18
 * Time: 17:18
 */


namespace App\Http\Controllers;



/**
 * 发送微信 模板消息
 */
class TempInfoController
{
    private $appid;
    private $appsecret;


    public function __construct()
    {
        $this->appid = config('other.appid');
        $this->appsecret = config('other.appsecret');
    }

    /**
     *获取  access_token  从微信获取
     */
    public function _getAccessToken(){
        $access_token = cache('access_token');
        if(!$access_token) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appid}&secret={$this->appsecret}";
            $data = $this->getCurl($url);
            $data = json_decode($data, true);

            $access_token = $data['access_token'];
            cache('access_token', $access_token, 3600);
        }
        return $access_token;
    }

    /**
     *获取  access_token  从文华获取，因为和文华接口冲突了
     */
    public function getAccessToken(){
        $access_token = cache('access_token');
        if(!$access_token) {
            $YzqLibObj = new YzqLib();
            $data = $YzqLibObj->getWxAccessToken();
            if($data['code'] === 200){
                $access_token = $data['content']['accessToken'];
                //获取下一个整点数
               // $end_time = getIntegralPointTime();
               // $diff_time = timediff( date('Y-m-d H:i:s'), $end_time ,false);
               // $time = $diff_time['min'] * 60 + $diff_time['sec'];//计算缓存秒数

                cache('access_token', $access_token, 5*60);//保存5分钟
            }
        }
        return $access_token;
    }


    /**
     * 发送模板消息   （图书馆借书通知）
     */
    public function sendTempInfoBorrowSuccess($data){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;

        $humpUrl = config('other.borrow_success');
        //推送的参数
        $param =[
            "touser"=>$data['openid'],
            "template_id"=>"T8_FU6qskdLPIymIxMhf-3qh4dX4stBGzWZlu-Kn71k",
            "url"=>$humpUrl,//跳转链接
          //  "url"=>'',//跳转链接
            "data"=>[
                 "first"=>[
                     "value"=>"书籍借阅成功！",
                     "color"=>"#57b382"
                   ],
                 "keyword1"=>[
                     "value"=>config('other.lib_name'),
                     "color"=>"#1d2122"
                   ],
                 "keyword2"=>[
                     "value"=>'《'.$data['book_name'].'》',
                     "color"=>"#1d2122"
                   ],
                 "keyword3"=>[
                     "value"=>$data['author'],
                     "color"=>"#1d2122"
                   ],
                 "keyword4"=>[
                    "value"=>$data['create_time'],
                    "color"=>"#1d2122"
                 ],
                 "keyword5"=>[
                    "value"=>$data['expire_time'],
                    "color"=>"#1d2122"
                 ],
                 "remark"=>[
                     "value"=>$data['msg'],
                     "color"=>"#2440B3"
                   ]
           ]
        ];
        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE),'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE),'template_push_log');

       // dump($result);die;
        /**
         * {
            "errcode":0,
            "errmsg":"ok",
            "msgid":200228332
            }
         */
        return $result;
    }
    /**
     * 发送模板消息   （图书馆还书成功通知）
     */
    public function sendTempInfoReturnSuccess($data){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;

        $humpUrl = config('other.return_success');
        //推送的参数
        $param =[
            "touser"=>$data['openid'],
            "template_id"=>"SNjeRaxyzs_lIIyH5AAOtPrkUgC5BVm_PFTzzTMV2Pk",
            "url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data"=>[
                "first"=>[
                    "value"=>"还书成功通知！",
                    "color"=>"#57b382"
                ],
                "keyword1"=>[
                    "value"=>config('other.lib_name'),
                    "color"=>"#1d2122"
                ],
                "keyword2"=>[
                    "value"=>'《'.$data['book_name'].'》',
                    "color"=>"#1d2122"
                ],
                "keyword3"=>[
                    "value"=>$data['author'],
                    "color"=>"#1d2122"
                ],
                "keyword4"=>[
                    "value"=>$data['return_time'],
                    "color"=>"#1d2122"
                ],
                "remark"=>[
                    "value"=>$data['msg'],
                    "color"=>"#2440B3"
                ]
            ]
        ];
        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE),'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE),'template_push_log');
        
        /**
         * {
        "errcode":0,
        "errmsg":"ok",
        "msgid":200228332
        }
         */
        return $result;
    }
    /**
     * 发送模板消息   （申请成功通知）
     */
    public function sendTempInfoApplySuccess($data){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;

        $humpUrl = config('other.apply_success').$data['link'];
        //推送的参数
        $param =[
            "touser"=>$data['openid'],
            "template_id"=>"XZXl5NiBjFERomEsIwzCE8o5qY0i-UQS5dG3dhzGfoo",
            "url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data"=>[
                "first"=>[
                    "value"=>"在线借阅申请成功！",
                    "color"=>"#57b382"
                ],
                "keyword1"=>[
                    "value"=>$data['username'],
                    "color"=>"#1d2122"
                ],
                "keyword2"=>[
                    "value"=>$data['msg'],
                    "color"=>"#1d2122"
                ],
                "keyword3"=>[
                    "value"=>$data['msg1'],
                    "color"=>"#1d2122"
                ],
                "keyword4"=>[
                    "value"=>$data['create_time'],
                    "color"=>"#1d2122"
                ],
                "remark"=>[
                    "value"=>$data['msg2'],
                    "color"=>"#2440B3"
                ]
            ]
        ];
        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE),'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE),'template_push_log');
        /**
         * {
        "errcode":0,
        "errmsg":"ok",
        "msgid":200228332
        }
         */
        return $result;
    }

    /**
     * 发送模板消息   （申请驳回通知）申请借阅失败
     */
    public function sendTempInfoApplyReject($data){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;

        $humpUrl = empty($data['link']) ? config('other.apply_reject1') : config('other.apply_reject').$data['link'];
        //推送的参数
        $param =[
            "touser"=>$data['openid'],
            "template_id"=>"JIuoF9kVqnPS75LzbvkoXrRV0jXi8behLS-kDzcY22c",
            "url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data"=>[
                "first"=>[
                    "value"=>"审核未通过通知！",
                    "color"=>"#eb5648"
                ],
                "keyword1"=>[
                    "value"=>$data['username'],
                    "color"=>"#1d2122"
                ],
                "keyword2"=>[
                    "value"=>$data['create_time'],
                    "color"=>"#1d2122"
                ],
                "keyword3"=>[
                    "value"=>$data['msg'],
                    "color"=>"#eb5648"
                ],
                "keyword4"=>[
                    "value"=>$data['msg1'],
                    "color"=>"#1d2122"
                ],
                "remark"=>[
                    "value"=>$data['msg2'],
                    "color"=>"#2440B3"
                ]
            ]
        ];
        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE),'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE),'template_push_log');
        /**
         * {
        "errcode":0,
        "errmsg":"ok",
        "msgid":200228332
        }
         */
        return $result;
    }

    /**
     * 发送模板消息   （图书馆续借成功通知）
     */
    public function sendTempInfoRenewSuccess($data){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;

        $humpUrl = config('other.renew_success');
        //推送的参数
        $param =[
            "touser"=>$data['openid'],
            "template_id"=>"Pj3WZYM2wg06YqM5U2i4qX46Mi-5QB7sZCD3dCRbeBI",
            "url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data"=>[
                "first"=>[
                    "value"=>"在线续借成功！",
                    "color"=>"#57b382"
                ],
                "keyword1"=>[
                    "value"=>config('other.lib_name'),
                    "color"=>"#1d2122"
                ],
                "keyword2"=>[
                    "value"=>'《'.$data['book_name'].'》',
                    "color"=>"#1d2122"
                ],
                "keyword3"=>[
                    "value"=>$data['author'],
                    "color"=>"#1d2122"
                ],
                "keyword4"=>[
                    "value"=>$data['return_time'],
                    "color"=>"#1d2122"
                ],
                "keyword5"=>[
                    "value"=>$data['number'],
                    "color"=>"#1d2122"
                ],
                "remark"=>[
                    "value"=>$data['msg'],
                    "color"=>"#2440B3"
                ]
            ]
        ];
        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);
        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE),'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE),'template_push_log');

       // dump($result);die;
        /**
         * {
        "errcode":0,
        "errmsg":"ok",
        "msgid":200228332
        }
         */
        return $result;
    }

    /**
     * 发送模板消息   （预约图书到馆通知）
     */
    public function sendTempInfoMakeInforms($data){
        $access_token = $this->getAccessToken();
        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token='.$access_token;

        $humpUrl = config('other.make_inform').'/'.$data['id'];
        //推送的参数
        $param =[
            "touser"=>$data['openid'],
            "template_id"=>"1GlY0x6Sa6Q6GziG6vbiKeQXy3QLMzY3oqTjHcmSR8U",
            "url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data"=>[
                "first"=>[
                    "value"=>"荐购图书到馆通知！",
                    "color"=>"#57b382"
                ],
                "keyword1"=>[
                    "value"=>'《'.$data['book_name'].'》',
                    "color"=>"#1d2122"
                ],
                "keyword2"=>[
                    "value"=>$data['create_time'],
                    "color"=>"#1d2122"
                ],
                "keyword3"=>[
                    "value"=>'线上荐购',
                    "color"=>"#1d2122"
                ],
                "remark"=>[
                    "value"=>$data['msg'],
                    "color"=>"#2440B3"
                ]
            ]
        ];
        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE),'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE),'template_push_log');

        /**
         * {
        "errcode":0,
        "errmsg":"ok",
        "msgid":200228332
        }
         */
        return $result;
    }

    /**
     * 发送服务提醒通知
     */
    public function sendServiceInfo($data)
    {
        set_time_limit(300);

        $access_token = $this->getAccessToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;

        //推送的参数
        $param = [
            "touser" => $data['openid'],
            "template_id" => "GB_NjnpSjZ0gPjoc3B1ulYHFmj7R-FJ8WKbPo_gskv4",
            //"url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data" => [
                "first" => [
                    "value" => $data['content'],
                    "color" => "#2440B3"
                ],
                "keyword1" => [
                    "value" => $data['type_name'],
                    "color" => "#1d2122"
                ],
                "keyword2" => [
                    "value" => $data['time'],
                    "color" => "#1d2122"
                ],
                /* "keyword3"=>[
                     "value"=>$time,
                     "color"=>"#1d2122"
                 ],*/
                /* "keyword4"=>[
                     "value"=>$data['addr'],
                     "color"=>"#1d2122"
                 ],*/
                "remark" => [
                    "value" => $data['remark'],
                    "color" => "#2440B3"
                ]
            ]
        ];
        //跳转链接                                            
        if (!empty($data['link'])) {
            $param['url'] = $data['link'];
        }

        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE), 'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE), 'template_push_log');

        return $result;
    }

    /**
     * 发送模板消息 (报名审核结果通知)
     * 
     * $state 1 成功  2 失败
     */
    public function sendActivityCheckInfo($data , $state)
    {
        $access_token = $this->getAccessToken();

        $url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=' . $access_token;

        //推送的参数
        $param = [
            "touser" => $data['openid'],
            "template_id" => "cDMdIoJYP1X14hFQNITQ44YvdXxeDelxYlCHY9WLsio",
            //"url"=>$humpUrl,//跳转链接
            //  "url"=>'',//跳转链接
            "data" => [
                "first" => [
                    "value" => $data['content'],
                   // "color" => $state == 1 ? "#1fa668" : "#df5146"
                ],
                "keyword1" => [
                    "value" => $data['act_name'],
                    "color" => "#1d2122"
                ],
                "keyword2" => [
                    "value" => $data['status'],
                    "color" => $state == 1 ? "#1fa668" : "#df5146"
                ],
                "keyword3" => [
                    "value" => $data['time'],
                    "color" => "#1d2122"
                ],
                "keyword4"=>[
                     "value"=>$data['addr'],
                     "color"=>"#1d2122"
                 ],
                "remark" => [
                    "value" => $data['remark'],
                    "color" => "#2440B3"
                ]
            ]
        ];
        //跳转链接                                            
        if (!empty($data['link'])) {
            $param['url'] = $data['link'];
        }

        $template_push_param = $param;
        $param = json_encode($param);
        $result = $this->getCurl($url , $param);
        $result = json_decode($result , true);

        //写入错误日志
        Log::write(json_encode($template_push_param , JSON_UNESCAPED_UNICODE), 'template_push_log');
        //写入错误日志
        Log::write(json_encode($result , JSON_UNESCAPED_UNICODE), 'template_push_log');

        return $result;
    }


    /**
     * curl方法
     * @param $url
     * @param $post_data
     * @param bool $true
     * @return mixed
     */
    private function getCurl($url,$post_data = null,$true=false){
       // if(!$true) $post_data=http_build_query($post_data);

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        if(!empty($post_data))
            curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);

        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    private function postCurl($url, $json)
    {
        $body = json_encode($json);
        $headers = array("Content-type: application/json;charset=UTF-8", "Accept: application/json", "Cache-Control: no-cache", "Pragma: no-cache");

        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }

}